package com.xrit;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ReadFormExcel {
    @Test
    public void exportExcel_lastRow() throws IOException {

        XSSFWorkbook sheets = new XSSFWorkbook(new FileInputStream(new File("d:\\work.xlsx")));

        XSSFSheet sheetAt = sheets.getSheetAt(0);
        int lastRowNum = sheetAt.getLastRowNum();
        for (int i = 0; i < lastRowNum; i++) {
            XSSFRow row = sheetAt.getRow(i);
            short lastCellNum = row.getLastCellNum();
            for (int j = 0; j < lastCellNum; j++) {
                row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
                String stringCellValue = row.getCell(j).getStringCellValue();
                System.out.print(stringCellValue+" ");
            }
            System.out.println();
        }
        sheets.close();
    }

    @Test
    public void createExcel() throws IOException {
        XSSFWorkbook sheets = new XSSFWorkbook();
        XSSFSheet excel = sheets.createSheet("测试写excel");
        XSSFRow row = excel.createRow(0);
        XSSFCell cell = row.createCell(0);
       cell.setCellValue("姓名");
        row.createCell(1).setCellValue("年龄");
        row.createCell(2).setCellValue("所在地");

        row=excel.createRow(1);
        row.createCell(0).setCellValue("张三");
        row.createCell(1).setCellValue(20);
        row.createCell(2).setCellValue("湖南");

        row=excel.createRow(2);
        row.createCell(0).setCellValue("小明");
        row.createCell(1).setCellValue(10);
        row.createCell(2).setCellValue("北京");

        sheets.write(new FileOutputStream(new File("d:\\work.xlsx")));
        sheets.close();
    }
}
